<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>PDF 转图片</title>
<!-- 本地引用Tailwind CSS -->
<script src="../../assets/js/tailwind.min.js"></script>
<style>
  .drag-drop-area {
    border: 2px dashed #cbd5e0;
    transition: all 0.3s;
  }
  .drag-drop-area.drag-over {
    border-color: #4299e1;
    background-color: #ebf8ff;
  }
</style>
</head>
<body class="bg-gray-50 min-h-screen p-6">
  <div class="max-w-2xl w-full mx-auto bg-white rounded-xl shadow-md overflow-hidden p-6 mt-8">
    <h1 class="text-2xl font-bold text-gray-800 mb-6 flex items-center">
      <span class="mr-2">🖼️</span> PDF转图片工具
    </h1>
    
    <div class="mb-6">
      <label class="block text-sm font-medium text-gray-700 mb-2">选择PDF文件（可多选）</label>
      <div class="drag-drop-area rounded-lg p-8 text-center" id="dragDropArea">
        <input type="file" id="upload" accept="application/pdf" multiple class="hidden">
        <label for="upload" 
               class="cursor-pointer bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg flex items-center transition-colors justify-center mx-auto w-fit">
          <span class="mr-2">📂</span> 选择文件
        </label>
        <p class="mt-4 text-gray-500">或拖拽文件到此处</p>
        <div id="fileList" class="mt-2 text-sm text-gray-500"></div>
      </div>
    </div>
    
    <div class="flex flex-wrap gap-3 mb-6">
      <button onclick="processPDF()" 
              class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg flex items-center transition-colors">
        <span class="mr-2">🔄</span> 开始转换
      </button>
      <button id="downloadBtn" onclick="downloadImages()" 
              class="bg-purple-500 hover:bg-purple-600 text-white px-4 py-2 rounded-lg flex items-center transition-colors hidden">
        <span class="mr-2">💾</span> 下载图片包
      </button>
    </div>
    
    <div class="progress-container bg-gray-200 rounded-full h-4 mb-6 hidden" id="progressContainer">
      <div class="progress-bar bg-blue-500 h-full rounded-full text-xs text-white flex items-center justify-center transition-all duration-300" 
           id="progressBar" style="width: 0%">0%</div>
    </div>
    
    <div id="status" class="p-4 rounded-lg hidden"></div>
  </div>

<!-- 依赖库 CDN -->
<!-- 本地引用pdf-lib.min.js，FileSaver.min.js -->
<script src="../../assets/js/pdf.min.js"></script>
<script src="../../assets/js/FileSaver.min.js"></script>
<script src="../../assets/js/jszip.min.js"></script>

<script>
let pdfFiles = {}; // 存储所有PDF文件及其转换结果

// 拖拽上传功能
const dragDropArea = document.getElementById('dragDropArea');
const fileInput = document.getElementById('upload');

// 拖拽事件处理
dragDropArea.addEventListener('dragover', (e) => {
  e.preventDefault();
  dragDropArea.classList.add('drag-over');
});

dragDropArea.addEventListener('dragleave', () => {
  dragDropArea.classList.remove('drag-over');
});

dragDropArea.addEventListener('drop', (e) => {
  e.preventDefault();
  dragDropArea.classList.remove('drag-over');
  
  if (e.dataTransfer.files.length) {
    fileInput.files = e.dataTransfer.files;
    updateFileList();
  }
});

// 监听文件上传事件
fileInput.addEventListener('change', function() {
  if (this.files.length > 0) {
    updateFileList();
  }
});

// 更新文件列表显示
function updateFileList() {
  const fileListDiv = document.getElementById('fileList');
  fileListDiv.innerHTML = '';
  
  if (fileInput.files.length === 0) {
    fileListDiv.textContent = '未选择文件';
    return;
  }
  
  const list = document.createElement('ul');
  list.className = 'space-y-1';
  
  Array.from(fileInput.files).forEach(file => {
    const item = document.createElement('li');
    item.className = 'flex items-center';
    item.innerHTML = `
      <span class="mr-2">📄</span>
      <span>${file.name}</span>
      <span class="ml-auto text-xs text-gray-400">${(file.size / 1024 / 1024).toFixed(2)} MB</span>
    `;
    list.appendChild(item);
  });
  
  fileListDiv.appendChild(list);
}

async function processPDF() {
  const files = fileInput.files;
  if (!files || files.length === 0) return alert('请先上传 PDF');
  
  // 初始化UI状态
  const progressContainer = document.getElementById('progressContainer');
  const progressBar = document.getElementById('progressBar');
  const statusDiv = document.getElementById('status');
  const downloadBtn = document.getElementById('downloadBtn');
  
  progressContainer.classList.remove('hidden');
  progressBar.style.width = '0%';
  progressBar.textContent = '0%';
  statusDiv.classList.add('hidden');
  downloadBtn.classList.add('hidden');
  
  try {
    // 清空之前的转换结果
    pdfFiles = {};
    
    // 处理每个PDF文件
    for (let fileIndex = 0; fileIndex < files.length; fileIndex++) {
      const file = files[fileIndex];
      const arrayBuffer = await file.arrayBuffer();
      const pdf = await pdfjsLib.getDocument({data: arrayBuffer}).promise;
      
      const pdfName = file.name.replace(/\.[^/.]+$/, ""); // 移除扩展名
      pdfFiles[pdfName] = {
        images: [],
        fileName: file.name
      };
      
      const totalPages = pdf.numPages;
      
      for (let i = 1; i <= totalPages; i++) {
        const page = await pdf.getPage(i);
        const scale = 2;
        const viewport = page.getViewport({scale});
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        canvas.width = viewport.width;
        canvas.height = viewport.height;
        await page.render({canvasContext: ctx, viewport}).promise;

        const dataURL = canvas.toDataURL('image/png');
        pdfFiles[pdfName].images.push(dataURL);
        
        // 更新进度条（所有文件的总进度）
        const totalProgress = Math.round(((fileIndex * totalPages + i) / (files.length * totalPages)) * 100);
        progressBar.style.width = totalProgress + '%';
        progressBar.textContent = totalProgress + '%';
      }
    }
    
    // 转换完成
    progressContainer.classList.add('hidden');
    statusDiv.textContent = `✅ 转换完成！共处理了 ${files.length} 个PDF文件。`;
    statusDiv.className = 'p-4 rounded-lg bg-green-100 text-green-800 border border-green-200';
    statusDiv.classList.remove('hidden');
    downloadBtn.classList.remove('hidden');
    
  } catch (error) {
    progressContainer.classList.add('hidden');
    statusDiv.textContent = `❌ 转换失败: ${error.message}`;
    statusDiv.className = 'p-4 rounded-lg bg-red-100 text-red-800 border border-red-200';
    statusDiv.classList.remove('hidden');
  }
}

function downloadImages() {
  if (Object.keys(pdfFiles).length === 0) return alert('请先转换 PDF');
  
  // 创建一个总的zip包
  const zip = new JSZip();
  
  // 为每个PDF创建子文件夹并添加图片
  Object.keys(pdfFiles).forEach(pdfName => {
    const folder = zip.folder(pdfName);
    
    pdfFiles[pdfName].images.forEach((data, idx) => {
      const base64 = data.split(',')[1];
      folder.file(`page-${idx + 1}.png`, base64, {base64: true});
    });
  });
  
  // 生成并下载zip文件
  zip.generateAsync({type: 'blob'}).then(blob => {
    saveAs(blob, 'pdf-images.zip');
    
    // 显示下载完成提示
    const statusDiv = document.getElementById('status');
    statusDiv.textContent = `✅ 已下载包含 ${Object.keys(pdfFiles).length} 个PDF图片的压缩包。`;
    statusDiv.className = 'p-4 rounded-lg bg-blue-100 text-blue-800 border border-blue-200';
    statusDiv.classList.remove('hidden');
  });
}
</script>
</body>
</html>
